home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / lib2to3 / pgen2 / tokenize.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  13.7 KB  |  422 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Tokenization help for Python programs.
  5.  
  6. generate_tokens(readline) is a generator that breaks a stream of
  7. text into Python tokens.  It accepts a readline-like method which is called
  8. repeatedly to get the next line of input (or "" for EOF).  It generates
  9. 5-tuples with these members:
  10.  
  11.     the token type (see token.py)
  12.     the token (a string)
  13.     the starting (row, column) indices of the token (a 2-tuple of ints)
  14.     the ending (row, column) indices of the token (a 2-tuple of ints)
  15.     the original line (string)
  16.  
  17. It is designed to match the working of the Python tokenizer exactly, except
  18. that it produces COMMENT tokens for comments and gives type OP for all
  19. operators
  20.  
  21. Older entry points
  22.     tokenize_loop(readline, tokeneater)
  23.     tokenize(readline, tokeneater=printtoken)
  24. are the same, except instead of generating tokens, tokeneater is a callback
  25. function to which the 5 fields described above are passed as 5 arguments,
  26. each time a new token is found.'''
  27. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  28. __credits__ = 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
  29. import string
  30. import re
  31. from lib2to3.pgen2.token import *
  32. from  import token
  33. __all__ = _[1] + [
  34.     'tokenize',
  35.     'generate_tokens',
  36.     'untokenize']
  37. del token
  38.  
  39. def group(*choices):
  40.     return '(' + '|'.join(choices) + ')'
  41.  
  42.  
  43. def any(*choices):
  44.     return group(*choices) + '*'
  45.  
  46.  
  47. def maybe(*choices):
  48.     return group(*choices) + '?'
  49.  
  50. Whitespace = '[ \\f\\t]*'
  51. Comment = '#[^\\r\\n]*'
  52. Ignore = Whitespace + any('\\\\\\r?\\n' + Whitespace) + maybe(Comment)
  53. Name = '[a-zA-Z_]\\w*'
  54. Binnumber = '0[bB][01]*'
  55. Hexnumber = '0[xX][\\da-fA-F]*[lL]?'
  56. Octnumber = '0[oO]?[0-7]*[lL]?'
  57. Decnumber = '[1-9]\\d*[lL]?'
  58. Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber)
  59. Exponent = '[eE][-+]?\\d+'
  60. Pointfloat = group('\\d+\\.\\d*', '\\.\\d+') + maybe(Exponent)
  61. Expfloat = '\\d+' + Exponent
  62. Floatnumber = group(Pointfloat, Expfloat)
  63. Imagnumber = group('\\d+[jJ]', Floatnumber + '[jJ]')
  64. Number = group(Imagnumber, Floatnumber, Intnumber)
  65. Single = "[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"
  66. Double = '[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'
  67. Single3 = "[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''"
  68. Double3 = '[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
  69. Triple = group("[ubUB]?[rR]?'''", '[ubUB]?[rR]?"""')
  70. String = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'", '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"')
  71. Operator = group('\\*\\*=?', '>>=?', '<<=?', '<>', '!=', '//=?', '->', '[+\\-*/%&|^=<>]=?', '~')
  72. Bracket = '[][(){}]'
  73. Special = group('\\r?\\n', '[:;.,`@]')
  74. Funny = group(Operator, Bracket, Special)
  75. PlainToken = group(Number, Funny, String, Name)
  76. Token = Ignore + PlainToken
  77. ContStr = group("[uUbB]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*" + group("'", '\\\\\\r?\\n'), '[uUbB]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*' + group('"', '\\\\\\r?\\n'))
  78. PseudoExtras = group('\\\\\\r?\\n', Comment, Triple)
  79. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  80. (tokenprog, pseudoprog, single3prog, double3prog) = map(re.compile, (Token, PseudoToken, Single3, Double3))
  81. endprogs = {
  82.     "'": re.compile(Single),
  83.     '"': re.compile(Double),
  84.     "'''": single3prog,
  85.     '"""': double3prog,
  86.     "r'''": single3prog,
  87.     'r"""': double3prog,
  88.     "u'''": single3prog,
  89.     'u"""': double3prog,
  90.     "b'''": single3prog,
  91.     'b"""': double3prog,
  92.     "ur'''": single3prog,
  93.     'ur"""': double3prog,
  94.     "br'''": single3prog,
  95.     'br"""': double3prog,
  96.     "R'''": single3prog,
  97.     'R"""': double3prog,
  98.     "U'''": single3prog,
  99.     'U"""': double3prog,
  100.     "B'''": single3prog,
  101.     'B"""': double3prog,
  102.     "uR'''": single3prog,
  103.     'uR"""': double3prog,
  104.     "Ur'''": single3prog,
  105.     'Ur"""': double3prog,
  106.     "UR'''": single3prog,
  107.     'UR"""': double3prog,
  108.     "bR'''": single3prog,
  109.     'bR"""': double3prog,
  110.     "Br'''": single3prog,
  111.     'Br"""': double3prog,
  112.     "BR'''": single3prog,
  113.     'BR"""': double3prog,
  114.     'r': None,
  115.     'R': None,
  116.     'u': None,
  117.     'U': None,
  118.     'b': None,
  119.     'B': None }
  120. triple_quoted = { }
  121. for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "b'''", 'b"""', "B'''", 'B"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""', "br'''", 'br"""', "Br'''", 'Br"""', "bR'''", 'bR"""', "BR'''", 'BR"""'):
  122.     triple_quoted[t] = t
  123.  
  124. single_quoted = { }
  125. for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "b'", 'b"', "B'", 'B"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"', "br'", 'br"', "Br'", 'Br"', "bR'", 'bR"', "BR'", 'BR"'):
  126.     single_quoted[t] = t
  127.  
  128. tabsize = 8
  129.  
  130. class TokenError(Exception):
  131.     pass
  132.  
  133.  
  134. class StopTokenizing(Exception):
  135.     pass
  136.  
  137.  
  138. def printtoken(type, token, .2, .3, line):
  139.     (srow, scol) = .2
  140.     (erow, ecol) = .3
  141.     print '%d,%d-%d,%d:\t%s\t%s' % (srow, scol, erow, ecol, tok_name[type], repr(token))
  142.  
  143.  
  144. def tokenize(readline, tokeneater = printtoken):
  145.     '''
  146.     The tokenize() function accepts two parameters: one representing the
  147.     input stream, and one providing an output mechanism for tokenize().
  148.  
  149.     The first parameter, readline, must be a callable object which provides
  150.     the same interface as the readline() method of built-in file objects.
  151.     Each call to the function should return one line of input as a string.
  152.  
  153.     The second parameter, tokeneater, must also be a callable object. It is
  154.     called once for each token, with five arguments, corresponding to the
  155.     tuples generated by generate_tokens().
  156.     '''
  157.     
  158.     try:
  159.         tokenize_loop(readline, tokeneater)
  160.     except StopTokenizing:
  161.         pass
  162.  
  163.  
  164.  
  165. def tokenize_loop(readline, tokeneater):
  166.     for token_info in generate_tokens(readline):
  167.         tokeneater(*token_info)
  168.     
  169.  
  170.  
  171. class Untokenizer:
  172.     
  173.     def __init__(self):
  174.         self.tokens = []
  175.         self.prev_row = 1
  176.         self.prev_col = 0
  177.  
  178.     
  179.     def add_whitespace(self, start):
  180.         (row, col) = start
  181.         if not row <= self.prev_row:
  182.             raise AssertionError
  183.         col_offset = col - self.prev_col
  184.         if col_offset:
  185.             self.tokens.append(' ' * col_offset)
  186.         
  187.  
  188.     
  189.     def untokenize(self, iterable):
  190.         for t in iterable:
  191.             if len(t) == 2:
  192.                 self.compat(t, iterable)
  193.                 break
  194.             
  195.             (tok_type, token, start, end, line) = t
  196.             self.add_whitespace(start)
  197.             self.tokens.append(token)
  198.             (self.prev_row, self.prev_col) = end
  199.             if tok_type in (NEWLINE, NL):
  200.                 self.prev_row += 1
  201.                 self.prev_col = 0
  202.                 continue
  203.             self
  204.         
  205.         return ''.join(self.tokens)
  206.  
  207.     
  208.     def compat(self, token, iterable):
  209.         startline = False
  210.         indents = []
  211.         toks_append = self.tokens.append
  212.         (toknum, tokval) = token
  213.         if toknum in (NAME, NUMBER):
  214.             tokval += ' '
  215.         
  216.         if toknum in (NEWLINE, NL):
  217.             startline = True
  218.         
  219.         for tok in iterable:
  220.             (toknum, tokval) = tok[:2]
  221.             if toknum in (NAME, NUMBER):
  222.                 tokval += ' '
  223.             
  224.             if toknum == INDENT:
  225.                 indents.append(tokval)
  226.                 continue
  227.             elif toknum == DEDENT:
  228.                 indents.pop()
  229.                 continue
  230.             elif toknum in (NEWLINE, NL):
  231.                 startline = True
  232.             elif startline and indents:
  233.                 toks_append(indents[-1])
  234.                 startline = False
  235.             
  236.             toks_append(tokval)
  237.         
  238.  
  239.  
  240.  
  241. def untokenize(iterable):
  242.     '''Transform tokens back into Python source code.
  243.  
  244.     Each element returned by the iterable must be a token sequence
  245.     with at least two elements, a token number and token value.  If
  246.     only two tokens are passed, the resulting output is poor.
  247.  
  248.     Round-trip invariant for full input:
  249.         Untokenized source will match input source exactly
  250.  
  251.     Round-trip invariant for limited intput:
  252.         # Output text will tokenize the back to the input
  253.         t1 = [tok[:2] for tok in generate_tokens(f.readline)]
  254.         newcode = untokenize(t1)
  255.         readline = iter(newcode.splitlines(1)).next
  256.         t2 = [tok[:2] for tokin generate_tokens(readline)]
  257.         assert t1 == t2
  258.     '''
  259.     ut = Untokenizer()
  260.     return ut.untokenize(iterable)
  261.  
  262.  
  263. def generate_tokens(readline):
  264.     '''
  265.     The generate_tokens() generator requires one argment, readline, which
  266.     must be a callable object which provides the same interface as the
  267.     readline() method of built-in file objects. Each call to the function
  268.     should return one line of input as a string.  Alternately, readline
  269.     can be a callable function terminating with StopIteration:
  270.         readline = open(myfile).next    # Example of alternate readline
  271.  
  272.     The generator produces 5-tuples with these members: the token type; the
  273.     token string; a 2-tuple (srow, scol) of ints specifying the row and
  274.     column where the token begins in the source; a 2-tuple (erow, ecol) of
  275.     ints specifying the row and column where the token ends in the source;
  276.     and the line on which the token was found. The line passed is the
  277.     logical line; continuation lines are included.
  278.     '''
  279.     lnum = parenlev = continued = 0
  280.     namechars = string.ascii_letters + '_'
  281.     numchars = '0123456789'
  282.     (contstr, needcont) = ('', 0)
  283.     contline = None
  284.     indents = [
  285.         0]
  286.     while None:
  287.         
  288.         try:
  289.             line = readline()
  290.         except StopIteration:
  291.             line = ''
  292.  
  293.         lnum = lnum + 1
  294.         pos = 0
  295.         max = len(line)
  296.         if contstr:
  297.             if not line:
  298.                 raise TokenError, ('EOF in multi-line string', strstart)
  299.             line
  300.             endmatch = endprog.match(line)
  301.             if endmatch:
  302.                 pos = end = endmatch.end(0)
  303.                 yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line)
  304.                 (contstr, needcont) = ('', 0)
  305.                 contline = None
  306.             elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  307.                 yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline)
  308.                 contstr = ''
  309.                 contline = None
  310.                 continue
  311.             else:
  312.                 contstr = contstr + line
  313.                 contline = contline + line
  314.         elif parenlev == 0 and not continued:
  315.             if not line:
  316.                 break
  317.             
  318.             column = 0
  319.             while pos < max:
  320.                 if line[pos] == ' ':
  321.                     column = column + 1
  322.                 elif line[pos] == '\t':
  323.                     column = (column / tabsize + 1) * tabsize
  324.                 elif line[pos] == '\x0c':
  325.                     column = 0
  326.                 else:
  327.                     break
  328.                 pos = pos + 1
  329.             if pos == max:
  330.                 break
  331.             
  332.             if line[pos] in '#\r\n':
  333.                 if line[pos] == '#':
  334.                     comment_token = line[pos:].rstrip('\r\n')
  335.                     nl_pos = pos + len(comment_token)
  336.                     yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line)
  337.                     yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line)
  338.                     continue
  339.                 yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line)
  340.                 continue
  341.             
  342.             if column > indents[-1]:
  343.                 indents.append(column)
  344.                 yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  345.             
  346.             while column < indents[-1]:
  347.                 if column not in indents:
  348.                     raise IndentationError('unindent does not match any outer indentation level', ('<tokenize>', lnum, pos, line))
  349.                 column not in indents
  350.                 indents = indents[:-1]
  351.                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  352.         elif not line:
  353.             raise TokenError, ('EOF in multi-line statement', (lnum, 0))
  354.         
  355.         continued = 0
  356.         while pos < max:
  357.             pseudomatch = pseudoprog.match(line, pos)
  358.             if pseudomatch:
  359.                 (start, end) = pseudomatch.span(1)
  360.                 spos = (lnum, start)
  361.                 epos = (lnum, end)
  362.                 pos = end
  363.                 token = line[start:end]
  364.                 initial = line[start]
  365.                 if (initial in numchars or initial == '.') and token != '.':
  366.                     yield (NUMBER, token, spos, epos, line)
  367.                 elif initial in '\r\n':
  368.                     newline = NEWLINE
  369.                     if parenlev > 0:
  370.                         newline = NL
  371.                     
  372.                     yield (newline, token, spos, epos, line)
  373.                 elif initial == '#':
  374.                     if not not token.endswith('\n'):
  375.                         raise AssertionError
  376.                     yield (COMMENT, token, spos, epos, line)
  377.                     not token.endswith('\n')
  378.                 elif token in triple_quoted:
  379.                     endprog = endprogs[token]
  380.                     endmatch = endprog.match(line, pos)
  381.                     if endmatch:
  382.                         pos = endmatch.end(0)
  383.                         token = line[start:pos]
  384.                         yield (STRING, token, spos, (lnum, pos), line)
  385.                     else:
  386.                         strstart = (lnum, start)
  387.                         contstr = line[start:]
  388.                         contline = line
  389.                         break
  390.                 elif initial in single_quoted and token[:2] in single_quoted or token[:3] in single_quoted:
  391.                     if token[-1] == '\n':
  392.                         strstart = (lnum, start)
  393.                         if not endprogs[initial] and endprogs[token[1]]:
  394.                             pass
  395.                         endprog = endprogs[token[2]]
  396.                         contstr = line[start:]
  397.                         needcont = 1
  398.                         contline = line
  399.                         break
  400.                     else:
  401.                         yield (STRING, token, spos, epos, line)
  402.                 elif initial in namechars:
  403.                     yield (NAME, token, spos, epos, line)
  404.                 elif initial == '\\':
  405.                     yield (NL, token, spos, (lnum, pos), line)
  406.                     continued = 1
  407.                 elif initial in '([{':
  408.                     parenlev = parenlev + 1
  409.                 elif initial in ')]}':
  410.                     parenlev = parenlev - 1
  411.                 
  412.                 yield (OP, token, spos, epos, line)
  413.                 continue
  414.             yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
  415.             pos = pos + 1
  416.         continue
  417.         for indent in indents[1:]:
  418.             yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  419.         
  420.     yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  421.  
  422.